package com.kmzx.one.project.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.service.WxPayService;
import com.kmzx.one.common.constants.Constants;
import com.kmzx.one.project.entity.UserOrder;
import com.kmzx.one.project.entity.UserRankBuy;
import com.kmzx.one.project.events.PayOrderEvent;
import com.kmzx.one.project.events.UserRankBuyEvent;
import com.kmzx.one.project.service.UserOrderService;
import com.kmzx.one.project.service.UserRanksService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Api(tags = "快美甄选_[ 支付回调_接口 ]")
@RestController
public class WXPayGateController extends BaseController {


    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    private RedisTemplate<String, Object> stringObjectRedisTemplate;

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private WxPayService wxService;

    @Autowired
    private UserRanksService userRanksService;


    @ApiOperation(value = "1.微信支付异步通知")
    @RequestMapping(value = "/wxPayCallback/{orderNo}", method = {RequestMethod.POST, RequestMethod.GET})
    public void handleCallBack(HttpServletRequest request, HttpServletResponse response, @PathVariable("orderNo") String orderNo) throws Exception {
        InputStream inputStream = request.getInputStream();
        String postData = IOUtils.toString(inputStream, "UTF-8");
        logger.info("微信支付,请求回调,回调数据为:" + postData);

        try {
            UserOrder userOrder = userOrderService.findUserOrderByCodes(orderNo);
            PrintWriter out = response.getWriter();
            String oks = WxPayNotifyResponse.success("成功");
            String nos = WxPayNotifyResponse.fail("失败");
            String ok = "SUCCESS";
            if (userOrder.getStates() == 1) {
                logger.info("微信支付,订单号:{},数据库状态为:已成功支付.默认响应成功", userOrder.getOrdersCodes());
                out.print(oks);
                out.close();
            } else {
//                final WxPayOrderNotifyResult notifyResult = this.wxService.parseOrderNotifyResult(postData);
//                // TODO 根据自己业务场景需要构造返回对象
//                String returnCode = notifyResult.getReturnCode();
//                String resultCode = notifyResult.getResultCode();
//                Date date = new Date();
//                PayOrderEvent orderEvent = new PayOrderEvent();
//                if (ok.equals(resultCode) && ok.equals(returnCode)) {
//                    logger.info("微信支付,订单号:{},数据库状态为:待支付.校验后返回:成功", userOrder.getOrdersCodes());
//                    userOrder.setStates(1);
//                    userOrder.setUpdateTime(date);
//                    userOrder.setFinishTime(date);
//                    orderEvent.setUserOrder(userOrder);
//
//                    applicationContext.publishEvent(orderEvent);
//
//                    StringBuilder stringBuilder = new StringBuilder(Constants.rewardOrderPrefix);
//                    stringBuilder.append(userOrder.getUserId() + "_" + userOrder.getTradeType()).append(",")
//                            .append(userOrder.getEndMoney()).append(",")
//                            .append(userOrder.getId()).append(",")
//                            .append(date.getTime()).append(",")
//                            .append("profit").append(",")
//                            .append("profit");
//                    // 订单倒计时
////                stringObjectRedisTemplate.opsForValue().set(stringBuilder.toString(),stringBuilder.toString(),24*7, TimeUnit.HOURS);
//                    stringObjectRedisTemplate.opsForValue().set(stringBuilder.toString(), stringBuilder.toString(), 10, TimeUnit.SECONDS);
//                    out.print(oks);
//                    out.close();
//                } else {
//                    logger.info("微信支付,订单号:{},数据库状态为:待支付.校验后返回:失败", userOrder.getOrdersCodes());
//                    userOrder.setStates(5);
//                    userOrder.setUpdateTime(date);
//                    userOrder.setFinishTime(date);
//                    applicationContext.publishEvent(orderEvent);
//                    out.print(nos);
//                    out.close();
//                }

                Date date = new Date();
                PayOrderEvent orderEvent = new PayOrderEvent();
                userOrder.setStates(1);
                    userOrder.setUpdateTime(date);
                    userOrder.setFinishTime(date);
                    orderEvent.setUserOrder(userOrder);

                    applicationContext.publishEvent(orderEvent);
                    StringBuilder stringBuilder = new StringBuilder(Constants.rewardOrderPrefix);
                    stringBuilder.append(userOrder.getUserId() + "_" + userOrder.getTradeType()).append(",")
                            .append(userOrder.getEndMoney()).append(",")
                            .append(userOrder.getId()).append(",")
                            .append(date.getTime()).append(",")
                            .append("profit").append(",")
                            .append("profit");
                    // 订单倒计时
//                stringObjectRedisTemplate.opsForValue().set(stringBuilder.toString(),stringBuilder.toString(),24*7, TimeUnit.HOURS);
                    stringObjectRedisTemplate.opsForValue().set(stringBuilder.toString(), stringBuilder.toString(), 10, TimeUnit.SECONDS);
                    out.print(oks);
                    out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @ApiOperation(value = "2.购买等级异步通知")
    @RequestMapping(value = "/rankBuyCallback/{orderId}", method = {RequestMethod.POST, RequestMethod.GET})
    public void handleRankBuyCallBack(HttpServletRequest request, HttpServletResponse response, @PathVariable("orderId") String orderId) throws Exception {
        InputStream inputStream = request.getInputStream();
        String postData = IOUtils.toString(inputStream, "UTF-8");
        logger.info("微信支付,请求回调,回调数据为:" + postData);

        UserRankBuy rankBuy = userRanksService.findUserRankBuy(orderId);

        PrintWriter out = response.getWriter();
        String oks = WxPayNotifyResponse.success("成功");
        String nos = WxPayNotifyResponse.fail("失败");
        String ok = "SUCCESS";
        Integer states = rankBuy.getStates();
        //　已经支付了
        if (states == 0) {
            logger.info("微信支付,订单号:{},数据库状态为:已成功支付.默认响应成功", rankBuy.getOrdersCode());
            out.print(oks);
            out.close();
        } else if (states == 1) {
             // // 待支付
            final WxPayOrderNotifyResult notifyResult = this.wxService.parseOrderNotifyResult(postData);
            // TODO 根据自己业务场景需要构造返回对象
            String resultCode = notifyResult.getResultCode();
            String returnCode = notifyResult.getReturnCode();
            Date date = new Date();
            if (ok.equals(resultCode) && ok.equals(returnCode)) {
                out.print(oks);
                rankBuy.setStates(0);
                rankBuy.setPayTime(date);
                rankBuy.setWxTradeNo(notifyResult.getTransactionId());
                UserRankBuyEvent userRankBuyEvent = new UserRankBuyEvent(rankBuy);
                applicationContext.publishEvent(userRankBuyEvent);
                out.close();
            } else {
                out.print(nos);
                out.close();
            }

//            rankBuy.setStates(0);
//            rankBuy.setPayTime(new Date());
//            rankBuy.setWxTradeNo("11111");
//            UserRankBuyEvent userRankBuyEvent = new UserRankBuyEvent(rankBuy);
//            applicationContext.publishEvent(userRankBuyEvent);
//            out.close();
        }
    }
}
